import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, Select, Space, Tag, Modal, message, Descriptions, Steps, Row, Col } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { Option } = Select;
const { Step } = Steps;

// 获取待处理订单列表
const fetchPendingOrders = async (params) => {
  return request('/api/v1/order/pending', {
    method: 'GET',
    params,
  });
};

// 获取订单详情
const fetchOrderDetail = async (id) => {
  return request(`/api/v1/order/${id}`, {
    method: 'GET',
  });
};

// 更新订单状态
const updateOrderStatus = async (data) => {
  return request('/api/v1/order/status', {
    method: 'POST',
    data,
  });
};

const OrderProcess = () => {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [statusForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [statusVisible, setStatusVisible] = useState(false);
  const [currentOrder, setCurrentOrder] = useState(null);
  const [targetStatus, setTargetStatus] = useState('');
  const [stores, setStores] = useState([]);
  const [venues, setVenues] = useState([]);
  const [members, setMembers] = useState([]);

  // 获取待处理订单列表
  const fetchOrderList = async () => {
    try {
      setLoading(true);
      const res = await fetchPendingOrders({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setOrders(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total,
        });
      } else {
        message.error(res.message || '获取待处理订单列表失败');
      }
    } catch (error) {
      console.error('获取待处理订单列表出错:', error);
      message.error('获取待处理订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取门店列表
  const fetchStoreList = async () => {
    try {
      const res = await request('/api/v1/store', {
        method: 'GET',
        params: { page: 1, pageSize: 1000 },
      });
      if (res.success) {
        setStores(res.data.list || []);
      } else {
        message.error(res.message || '获取门店列表失败');
      }
    } catch (error) {
      console.error('获取门店列表出错:', error);
      message.error('获取门店列表失败');
    }
  };

  // 获取关联数据
  const fetchRelatedData = async (orderList) => {
    try {
      // 提取会员ID、场地ID
      const memberIds = Array.from(new Set(orderList.map(order => order.member_id).filter(Boolean)));
      const venueIds = Array.from(new Set(orderList.map(order => order.venue_id).filter(Boolean)));
      
      // 如果有会员ID，获取会员信息
      if (memberIds.length > 0) {
        const memberRes = await request('/api/v1/member/batch', {
          method: 'POST',
          data: { ids: memberIds },
        });
        if (memberRes.success && memberRes.data) {
          setMembers(memberRes.data);
        }
      }
      
      // 如果有场地ID，获取场地信息
      if (venueIds.length > 0) {
        const venueRes = await request('/api/v1/venue/batch', {
          method: 'POST',
          data: { ids: venueIds },
        });
        if (venueRes.success && venueRes.data) {
          setVenues(venueRes.data);
        }
      }
    } catch (error) {
      console.error('获取关联数据出错:', error);
    }
  };

  useEffect(() => {
    fetchOrderList();
    fetchStoreList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 当订单列表更新时，获取关联数据
  useEffect(() => {
    if (orders && orders.length > 0) {
      fetchRelatedData(orders);
    }
  }, [orders]);

  // 查看订单详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchOrderDetail(record.id);
      if (res.success) {
        setCurrentOrder(res.data);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取订单详情失败');
      }
    } catch (error) {
      console.error('获取订单详情出错:', error);
      message.error('获取订单详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理状态变更
  const handleStatusChange = (record, status) => {
    setCurrentOrder(record);
    setTargetStatus(parseInt(status));
    statusForm.resetFields();
    setStatusVisible(true);
  };

  // 提交状态变更
  const handleStatusSubmit = async () => {
    try {
      const values = await statusForm.validateFields();
      setLoading(true);

      const data = {
        id: currentOrder.id,
        status: targetStatus,
        remark: values.remark,
      };

      const res = await updateOrderStatus(data);
      if (res.success) {
        message.success('订单状态更新成功');
        setStatusVisible(false);
        fetchOrderList();
      } else {
        message.error(res.message || '订单状态更新失败');
      }
    } catch (error) {
      console.error('订单状态更新出错:', error);
      message.error('订单状态更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.keyword) {
      params.keyword = values.keyword;
    }
    if (values.status) {
      params.status = values.status;
    }

    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };

  // 获取订单状态步骤
  const getOrderSteps = (status) => {
    let current = 0;
    switch (status) {
      case 1:
        current = 0;
        break;
      case 2:
        current = 1;
        break;
      case 3:
        current = 2;
        break;
      case 4:
        current = 3;
        break;
      default:
        current = 0;
    }

    return (
      <Steps current={current} size="small">
        <Step title="待处理" />
        <Step title="处理中" />
        <Step title="已完成" />
        {status === 4 && <Step title="已取消" status="error" />}
      </Steps>
    );
  };

  // 获取门店名称
  const getStoreName = (storeId) => {
    const store = stores.find(s => s.id === storeId);
    return store ? store.name : storeId;
  };

  // 获取场地名称
  const getVenueName = (venueId) => {
    const venue = venues.find(v => v.id === venueId);
    return venue ? venue.name : venueId;
  };

  // 获取会员名称
  const getMemberName = (memberId, record) => {
    const member = members.find(m => m.id === memberId);
    if (member) {
      return `${member.name}[${member.phone}]`;
    }
    return record?.user_name || memberId;
  };

  // 获取订单状态文本
  const getOrderStatusText = (status) => {
    switch (parseInt(status)) {
      case 1:
        return <Tag color="gold">待处理</Tag>;
      case 2:
        return <Tag color="blue">处理中</Tag>;
      case 3:
        return <Tag color="green">已完成</Tag>;
      case 4:
        return <Tag color="red">已取消</Tag>;
      default:
        return <Tag color="default">未知状态</Tag>;
    }
  };

  // 获取支付状态文本
  const getPaymentStatusText = (status) => {
    switch (status) {
      case 'unpaid':
        return <Tag color="default">未支付</Tag>;
      case 'paid':
        return <Tag color="green">已支付</Tag>;
      case 'refunded':
        return <Tag color="orange">已退款</Tag>;
      default:
        return <Tag color="default">未知状态</Tag>;
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '订单号',
      dataIndex: 'order_no',
      key: 'order_no',
      width: 180,
    },
    {
      title: '门店',
      dataIndex: 'store_id',
      key: 'store_id',
      width: 150,
      render: (storeId) => {
        const store = stores.find(s => s.id === storeId);
        return store ? store.name : storeId;
      },
    },
    {
      title: '场地',
      dataIndex: 'venue_id',
      key: 'venue_id',
      width: 150,
      render: (venueId) => {
        const venue = venues.find(v => v.id === venueId);
        return venue ? venue.name : venueId;
      },
    },
    {
      title: '会员',
      dataIndex: 'member_id',
      key: 'member_id',
      width: 120,
      render: (memberId, record) => {
        return getMemberName(memberId,record);
      },
    },
    {
      title: '订单金额',
      dataIndex: 'total_amount',
      key: 'total_amount',
      width: 120,
      render: (text) => `¥${(text / 100).toFixed(2)}`,
    },
    {
      title: '支付状态',
      dataIndex: 'payment_status',
      key: 'payment_status',
      width: 100,
      render: (status) => {
        let color = '';
        let text = '';
        switch (status) {
          case 'unpaid':
            color = 'default';
            text = '未支付';
            break;
          case 'paid':
            color = 'green';
            text = '已支付';
            break;
          case 'refunded':
            color = 'orange';
            text = '已退款';
            break;
          default:
            color = 'default';
            text = status;
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        let color = '';
        let text = '';
        switch (status) {
          case 1:
            color = 'gold';
            text = '待处理';
            break;
          case 2:
            color = 'blue';
            text = '处理中';
            break;
          case 3:
            color = 'green';
            text = '已完成';
            break;
          case 4:
            color = 'red';
            text = '已取消';
            break;
          default:
            color = 'default';
            text = '未知';
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '下单时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render:(val)=>moment(val*1000).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        const actions = [
          <Button
            key="view"
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
        ];

        // 根据订单状态显示不同的操作按钮
        if (record.status === 1) {
          actions.push(
            <Button
              key="process"
              type="link"
              icon={<CheckOutlined />}
              style={{ color: '#1890ff' }}
              onClick={() => handleStatusChange(record, 2)}
            >
              处理
            </Button>
          );
        }

        if (record.status === 2) {
          actions.push(
            <Button
              key="complete"
              type="link"
              icon={<CheckOutlined />}
              style={{ color: '#52c41a' }}
              onClick={() => handleStatusChange(record, 3)}
            >
              完成
            </Button>
          );
        }

        // 待处理和处理中的订单可以取消
        if (record.status === 1 || record.status === 2) {
          actions.push(
            <Button
              key="cancel"
              type="link"
              icon={<CloseOutlined />}
              danger
              onClick={() => handleStatusChange(record, 4)}
            >
              取消
            </Button>
          );
        }

        return <Space>{actions}</Space>;
      },
    },
  ];

  // 订单详情模态框
  const renderDetailModal = () => {
    if (!currentOrder) return null;

    return (
      <Modal
        title="订单详情"
        visible={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={700}
      >
        <Descriptions bordered column={2}>
          <Descriptions.Item label="订单号">{currentOrder.order_no}</Descriptions.Item>
          <Descriptions.Item label="状态">{getOrderStatusText(currentOrder.status)}</Descriptions.Item>
          <Descriptions.Item label="门店">{getStoreName(currentOrder.store_id)}</Descriptions.Item>
          <Descriptions.Item label="场地">{getVenueName(currentOrder.venue_id)}</Descriptions.Item>
          <Descriptions.Item label="会员">{getMemberName(currentOrder.member_id, currentOrder)}</Descriptions.Item>
          <Descriptions.Item label="支付状态">{getPaymentStatusText(currentOrder.payment_status)}</Descriptions.Item>
          <Descriptions.Item label="订单金额">¥{(currentOrder.total_amount / 100).toFixed(2)}</Descriptions.Item>
          <Descriptions.Item label="下单时间">{moment(currentOrder.created_at * 1000).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
          <Descriptions.Item label="预约开始时间" span={2}>
            {currentOrder.start_time ? moment(currentOrder.start_time * 1000).format('YYYY-MM-DD HH:mm:ss') : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="预约结束时间" span={2}>
            {currentOrder.end_time ? moment(currentOrder.end_time * 1000).format('YYYY-MM-DD HH:mm:ss') : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="备注" span={2}>{currentOrder.remark || '-'}</Descriptions.Item>
        </Descriptions>
      </Modal>
    );
  };

  return (
    <PageContainer>
      <Card title="订单处理" extra={
        <Space>
          <Button type="primary" icon={<SearchOutlined />} onClick={() => form.submit()}>搜索</Button>
          <Button type="primary" icon={<ReloadOutlined />} onClick={fetchOrderList}>刷新</Button>
        </Space>
      }>
        <Form form={form} layout="inline" onFinish={handleSearch} style={{ marginBottom: 24 }}>
          <Form.Item name="keyword" label="关键字">
            <Input placeholder="订单号、会员名" />
          </Form.Item>
          <Form.Item name="status" label="订单状态">
            <Select placeholder="请选择订单状态" style={{ width: 160 }}>
              <Option value="1">待处理</Option>
              <Option value="2">处理中</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
        />
      </Card>

      {renderDetailModal()}
      <Modal
        title="订单状态变更"
        visible={statusVisible}
        onCancel={() => setStatusVisible(false)}
        footer={null}
        width={600}
      >
        {currentOrder && (
          <Form form={statusForm} layout="vertical">
            <Form.Item label="订单状态">
              {targetStatus === '2' ? (
                <Tag color="blue">处理中</Tag>
              ) : targetStatus === '3' ? (
                <Tag color="green">已完成</Tag>
              ) : (
                <Tag color="red">已取消</Tag>
              )}
            </Form.Item>
            <Form.Item label="备注">
              <Input.TextArea rows={4} />
            </Form.Item>
            <Form.Item> 
              <Button type="primary" htmlType="submit" onClick={handleStatusSubmit}>
                提交          
                </Button>
            </Form.Item>
          </Form>
        )}
      </Modal>
    </PageContainer>
  );
};
export default OrderProcess;